//
//  RegisterInfoViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/20.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "RegisterInfoViewController.h"
#import "MainViewController.h"
#import "RegionViewController.h"

//Cell
#import "RegisterCell.h"

//Request
#import "HTTPPromise+Login.h"

//Model
#import "WXAuth2Model.h"

//Tools
#import "UIViewController+KeyboardCorver.h"
#import "AppUtil.h"

@interface RegisterInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,RegionCodeParamsDelegate,RegisterCellDelegate>
{
    int areaCode;               //区域代码
}
@property (strong, nonatomic) IBOutlet UITableView *RegisterInfoTableView;
@property (strong, nonatomic) Region2Model *model;

@end

@implementation RegisterInfoViewController

#pragma mark -init
#define RegisterIdentifyCell @"RegisterCell"

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Xib
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([RegisterCell class])
                                bundle:[NSBundle mainBundle]];
    [_RegisterInfoTableView registerNib:nib forCellReuseIdentifier:RegisterIdentifyCell];
    
    areaCode = 0;
    [self initTableView];
    [self addNotification];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"请完善个人信息"];
    [self addNavigationRightView:@"下一步"];
}

- (void)initTableView
{
    _RegisterInfoTableView.tableFooterView = [[UIView alloc] init];
//    _RegisterInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    _RegisterInfoTableView.scrollEnabled = NO;
}

#pragma mark -tableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0 && indexPath.row != 5) {
        RegisterCell *registerCell = [tableView dequeueReusableCellWithIdentifier:RegisterIdentifyCell];
        [registerCell configureCell:indexPath.row];
        registerCell.selectionStyle = UITableViewCellSelectionStyleNone;
        registerCell.cellDelegate = self;
        if(indexPath.row == 2){
            [[registerCell viewWithTag:102] removeFromSuperview];
            registerCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        return registerCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, 40)];
        
        label.numberOfLines  = 0;
        label.font = [UIFont boldSystemFontOfSize:14.0f];
        label.lineBreakMode = NSLineBreakByWordWrapping;
        label.textAlignment = NSTextAlignmentLeft;
        
        if(indexPath.row == 0)
        {
            label.text = @"请完善您的个人信息并保证信息的真实有效性,一旦提交无法自行修改,如需修改请致电000000";
        }else{
            label.text = @"注:手机号码前面已经绑定，此处不可修改，其他信息可修改";
            label.textColor = [UIColor redColor];
        }
        
        if (indexPath.row == 5) {
            cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell addSubview:label];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0 || indexPath.row == 5){
        return 60;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0 || indexPath.row == 5){
        return 60;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.row);
    if (indexPath.row == 2) {
        RegionViewController *regionVC = [[RegionViewController alloc] init];
        regionVC.citydelegate = self;
        if(_model != nil)
        {
            [regionVC setValue:_model forKey:@"paramModel"];
        }
        
        if (self.presentingViewController) {
            [self.navigationController presentViewController:regionVC animated:YES completion:nil];
        }else{
            [self.navigationController pushViewController:regionVC animated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -Action
- (void)rightTapAction {
    UITextField *nickText = [self.RegisterInfoTableView viewWithTag:101];
    NSString *nickStr = nickText.text;
    
    if(!HTCFVerifyNickName(nickStr)){
        [AppUtil showTipMessage:@"请输入正确的昵称"];
        return ;
    }
    
    if(areaCode == 0){
        [AppUtil showTipMessage:@"请选择城市"];
        return ;
    }
    
    UITextField *userText = [self.RegisterInfoTableView viewWithTag:103];
    NSString *userStr = userText.text;
    if(HTCFStringIsNull(userStr)){
        [AppUtil showTipMessage:@"请输入真实姓名"];
        return ;
    }
    
    NSDictionary *registerParam = @{@"nick":nickStr,@"regionId":[NSNumber numberWithInt:areaCode],@"realName":userStr};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:registerParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:registerParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requesSaveMyInfoParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        
        if (successRet == 0) {
            [strongSelf skipController];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController
{
    if (self.presentingViewController) {
//        UIViewController * presentingViewController = self.presentingViewController;
//        while (presentingViewController.presentingViewController) {
//            presentingViewController = presentingViewController.presentingViewController;
//        }
//        [presentingViewController dismissViewControllerAnimated:YES completion:nil];
        UIViewController *vc =  self;
        while (vc.presentingViewController) {
            vc = vc.presentingViewController;
        }
        NSLog(@"vc:========%@",vc);
        [vc dismissViewControllerAnimated:YES completion:nil];
    }else{
        MainViewController *mainVC = [[MainViewController alloc] init];
        [self.navigationController pushViewController:mainVC animated:YES];
    }
}

- (IBAction)backAction:(UITapGestureRecognizer *)sender {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -
- (void)clickCell{
    RegionViewController *regionVC = [[RegionViewController alloc] init];
    regionVC.citydelegate = self;
    if(_model != nil)
    {
        [regionVC setValue:_model forKey:@"paramModel"];
    }
    
    if (self.presentingViewController) {
        [self.navigationController presentViewController:regionVC animated:YES completion:nil];
    }else{
        [self.navigationController pushViewController:regionVC animated:YES];
    }
}

#pragma mark -textFieldDelegate
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [[self view] endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -RegionCodeParamsDelegate
- (void)transmitCity:(Region2Model *)model
{
    NSLog(@"model:%@",model.name);
    areaCode = [model.rId intValue];
    UIButton *btn = [_RegisterInfoTableView viewWithTag:112];
    
    [btn setTitle:model.name forState:UIControlStateNormal];
    
    _model = [[Region2Model alloc] init];
    _model = model;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
